<template>
  <view class="community-container">
    <!-- 动态列表 -->
    <view class="community-list">
      <view v-for="(item, index) in communityList" :key="item.id" class="community-item" @click="goToDynamicDetail(item.id)">
        <!-- 用户信息和发布时间 -->
        <view class="user-info-header">
          <view class="user-info">
            <image class="avatar" :src="item.avatar" mode="aspectFill" @click.stop="goToProfile(item.userId)"></image>
            <text class="username">{{ item.userName || '用户' + item.userId }}</text>
          </view>
          <text class="publish-time">{{ formatTime(item.publishTime) || '时间未知' }}</text>
        </view>
        <!-- 动态内容 -->
        <text class="content">{{ item.content }}</text>
        
        <!-- 媒体内容区域 -->
        <view class="media-container">
          
          <view v-if="item.video && item.video.length > 0" class="video-list">
            <video v-for="(video, videoIndex) in item.video" :key="videoIndex" :src="video" controls></video>
          </view>
          
          <!-- 图片展示 -->
          <view v-else-if="item.images && item.images.length > 0" class="wechat-image-grid" :class="getImageGridClass(item.images.length)">
            <image 
              v-for="(img, imgIndex) in item.images" 
              :key="imgIndex" 
:src="img" 
              mode="aspectFill"
              class="wechat-image"
              @click.stop="previewImage(item.images, imgIndex)"
            ></image>
          </view>
        </view>
        
        <!-- 动态操作（收藏、评论、点赞、转发） -->
        <view class="post-actions" @click.stop>
          <view class="action-item" @click="toggleFavorite(item)">
            <image class="action-icon" :src="item.isFavorite ? '/static/star-filled.png' : '/static/star.png'" mode="aspectFit"></image>
            <text class="action-text">{{ item.favoriteCount }}</text>
          </view>
          <view class="action-item">
            <image class="action-icon" src="/static/comment.png" mode="aspectFit"></image>
            <text class="action-text">{{ item.commentCount }}</text>
          </view>
          <view class="action-item" @click="toggleLike(item)">
            <image class="action-icon" :src="item.isLiked ? '/static/like-filled.png' : '/static/like.png'" mode="aspectFit"></image>
            <text class="action-text">{{ item.likeCount }}</text>
          </view>
          <view class="action-item">
            <image class="action-icon" src="/static/share.png" mode="aspectFit"></image>
            <text class="action-text">{{ item.shareCount }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="total > 0 && total > communityList.length" class="load-more" @click="loadMore">
      加载更多
    </view>
    <view v-else-if="communityList && communityList.length > 0" class="no-more-data">
      没有更多数据了
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
// import CommunityUtil from '@/sheep/api/index/community'
import userStore from '@/sheep/store/user'

// 定义 props
const props = defineProps({
  userId: {
    type: [String, Number],
    default: ''
  }
})

// 社区动态相关数据
const communityList = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 获取社区动态数据
const getCommunityData = async () => {
  loading.value = true
  
  try {
    const CommunityUtil = (await import('@/sheep/api/index/community')).default
    // 统一调用page接口，如果有userId（且不为空字符串）就传过去
    const requestParams = {
      page: page.value,
      pageSize: pageSize.value
    }
    // 只有当userId存在且不为空字符串时才传入
    if (props.userId && props.userId !== '') {
      requestParams.userId = props.userId
    }
    const res = await CommunityUtil.getCommunityList(requestParams)
    
    const listData = res.data?.list || []
    const totalData = res.data?.total || 0
    
    if (page.value === 1) {
      communityList.value = listData
    } else {
      communityList.value = [...communityList.value, ...listData]
    }
    total.value = totalData
    
    communityList.value.forEach(item => {
      if (item.images && typeof item.images === 'string') {
        item.images = item.images.split(',')
      }
      if (item.video && typeof item.video === 'string') {
        item.video = item.video.split(',')
      }
      item.isFavorite = !!item.favorited
      if (item.hasOwnProperty('liked')) {
        item.isLiked = !!item.liked
      } else {
        // 如果没有liked字段，保持原有逻辑或设为false
        item.isLiked = item.isLiked || false
      }
    })
    
    // 如果用户已登录，检查每个项目的点赞和收藏状态
    // if (userStore().isLogin) {
    //   for (const item of communityList.value) {
    //     await checkItemStatus(item)
    //   }
    // }
  } catch (error) {
    console.error('获取社区动态失败:', error)
    uni.showToast({
      title: '获取动态失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 监听 userId 变化，重新加载数据
watch(() => props.userId, (newUserId, oldUserId) => {
  if (newUserId && newUserId !== '') {
    if (!oldUserId || oldUserId === '' || newUserId !== oldUserId) {
      page.value = 1
      communityList.value = []
      total.value = 0
      getCommunityData()
    }
  }
})

onMounted(() => {
  getCommunityData()
})

// 刷新列表（重置到第一页）
const refresh = () => {
  page.value = 1
  communityList.value = []
  total.value = 0
  getCommunityData()
}

// 加载更多
const loadMore = () => {
  console.log('loadMore 被调用，当前状态:', {
    listLength: communityList.value.length,
    total: total.value,
    loading: loading.value,
    page: page.value
  })
  
  // 如果已经加载完所有数据或正在加载中，直接返回（不显示提示，避免频繁提示）
  if (total.value > 0 && communityList.value.length >= total.value) {
    console.log('已加载完所有数据，停止加载')
    return
  }
  
  if (loading.value) {
    console.log('正在加载中，跳过本次请求')
    return
  }
  
  console.log('开始加载第', page.value + 1, '页')
  page.value++
  getCommunityData()
}

// 滚动到底部时触发（保留用于 scroll-view，如果将来需要）
const handleScrollToLower = () => {
  console.log('滚动到底部，触发加载更多')
  console.log('当前列表长度:', communityList.value.length, '总数:', total.value, '当前页:', page.value)
  loadMore()
}

// 暴露方法给父组件
defineExpose({
  getCommunityData,
  loadMore,
  refresh
})

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  
  let time;
  
  // 处理时间戳（毫秒）
  if (typeof timeStr === 'number' && timeStr > 0) {
    time = new Date(timeStr);
  } 
  // 处理字符串时间戳
  else if (typeof timeStr === 'string' && !isNaN(timeStr)) {
    time = new Date(parseInt(timeStr));
  }
  // 处理ISO字符串
  else if (typeof timeStr === 'string') {
    time = new Date(timeStr);
  } 
  // 处理其他格式
  else {
    return '';
  }
  
  // 检查日期是否有效
  if (isNaN(time.getTime())) {
    return '';
  }
  
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
  const diff = now.getTime() - time.getTime();
  
  // 1分钟内：刚刚
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  // 1小时内：几分钟前
  else if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000));
    return `${minutes}分钟前`;
  }
  // 24小时内：几小时前
  else if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000));
    return `${hours}小时前`;
  }
  // 昨天：显示"昨天"
  else if (time.getTime() >= yesterday.getTime() && time.getTime() < today.getTime()) {
    return '昨天';
  }
  // 48小时内：显示"前天"或继续显示小时
  else if (diff < 48 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000));
    if (hours < 48) {
      return `${hours}小时前`;
    }
  }
  // 同一年：显示月-日（如：12-25）
  else if (time.getFullYear() === now.getFullYear()) {
    const month = time.getMonth() + 1;
    const day = time.getDate();
    return `${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
  }
  // 跨年：显示年-月-日（如：2023-12-25）
  else {
    const year = time.getFullYear();
    const month = time.getMonth() + 1;
    const day = time.getDate();
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
  }
  
  // 默认返回天数
  const days = Math.floor(diff / (24 * 60 * 60 * 1000));
  return `${days}天前`;
}

// 获取图片网格布局类名（微信朋友圈标准）
const getImageGridClass = (imageCount) => {
  if (imageCount === 1) return 'single-image';
  if (imageCount === 2) return 'double-image';
  if (imageCount === 3) return 'triple-image';
  if (imageCount === 4) return 'quadruple-image';
  if (imageCount === 5) return 'five-image';
  if (imageCount === 6) return 'six-image';
  if (imageCount === 7) return 'seven-image';
  if (imageCount === 8) return 'eight-image';
  if (imageCount === 9) return 'nine-image';
  return 'multi-image'; // 超过9张
}

// 预览图片
const previewImage = (images, currentIndex) => {
  uni.previewImage({
    urls: images,
    current: currentIndex
  });
}

const goToDynamicDetail = (dynamicId) => {
  uni.navigateTo({
    url: `/pages/dynamic/detail?id=${dynamicId}`
  })
}

// 跳转到个人主页
const goToProfile = (userId) => {
  if (!userId) return
  uni.navigateTo({
    url: `/pages/user/profile?userId=${userId}`
  })
}

// 切换收藏状态
const toggleFavorite = async (item) => {
  // 检查用户是否登录
  if (!userStore().isLogin) {
    // 跳转到登录页面
    uni.navigateTo({
      url: '/pages/index/login'
    })
    return
  }
  
  try {
    const CommunityUtil = (await import('@/sheep/api/index/community')).default
    // 根据当前状态调用不同的API
    if (item.isFavorite) {
      // 取消收藏
      await CommunityUtil.cancelFavorite({ id: item.id })
      item.isFavorite = false
      item.favoriteCount = Math.max(0, (item.favoriteCount || 1) - 1)
    } else {
      // 添加收藏
      const CommunityUtil = (await import('@/sheep/api/index/community')).default
      await CommunityUtil.createFavorite({ id: item.id })
      item.isFavorite = true
      item.favoriteCount = (item.favoriteCount || 0) + 1
    }
    
    // 操作成功提示
    uni.showToast({
      title: item.isFavorite ? '收藏成功' : '取消收藏成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('收藏操作失败:', error)
    // 恢复原来的状态
    item.isFavorite = !item.isFavorite
    
    uni.showToast({
      title: item.isFavorite ? '收藏失败' : '取消收藏失败',
      icon: 'none'
    })
  }
}

// 切换点赞状态
const toggleLike = async (item) => {
  // 检查用户是否登录
  if (!userStore().isLogin) {
    // 跳转到登录页面
    uni.navigateTo({
      url: '/pages/index/login'
    })
    return
  }
  
  try {
    // 根据当前状态调用不同的API
    if (item.isLiked) {
      // 取消点赞
      const CommunityUtil = (await import('@/sheep/api/index/community')).default
      await CommunityUtil.cancelLike({ id: item.id })
      item.isLiked = false
      item.likeCount = Math.max(0, (item.likeCount || 1) - 1)
    } else {
      // 添加点赞
      const CommunityUtil = (await import('@/sheep/api/index/community')).default
      await CommunityUtil.createLike({ id: item.id })
      item.isLiked = true
      item.likeCount = (item.likeCount || 0) + 1
    }
    
    // 操作成功提示
    uni.showToast({
      title: item.isLiked ? '点赞成功' : '取消点赞成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('点赞操作失败:', error)
    // 恢复原来的状态
    item.isLiked = !item.isLiked
    
    uni.showToast({
      title: item.isLiked ? '点赞失败' : '取消点赞失败',
      icon: 'none'
    })
  }
}

// 在获取数据后检查点赞和收藏状态
// const checkItemStatus = async (item) => {
//   try {
//     // 检查点赞状态
//     const likeStatus = await CommunityUtil.isLiked({ id: item.id })
//     item.isLiked = likeStatus.data || false
    
//     // 检查收藏状态
//     const favoriteStatus = await CommunityUtil.isFavorite({ id: item.id })
//     item.isFavorite = favoriteStatus.data || false
//   } catch (error) {
//     console.error('检查状态失败:', error)
//   }
// }
</script>

<style scoped>
.community-container {
  width: 100%;
  padding: 0rpx 0rpx 120rpx;
}

.community-list {
  padding: 0 0rpx;
}

.community-item {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.user-info-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  background-color: #f0f0f0;
  border-radius: 50%;
  margin-right: 15rpx;
}

.username {
  font-size: 28rpx;
  font-weight: 500;
}

.publish-time {
  font-size: 22rpx;
  color: #999;
  align-self: flex-start;
}

.content {
  font-size: 28rpx;
  line-height: 44rpx;
  margin-bottom: 20rpx;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-list video {
  width: 100%;
  height: 400rpx;
  margin-bottom: 10rpx;
  border-radius: 10rpx;
}

.no-more-data {
  text-align: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 24rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

/* 媒体容器 */
.media-container {
  margin: 20rpx 0;
}

/* 微信朋友圈图片网格布局 */
.wechat-image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 4rpx;
  width: 100%;
}

/* 单张图片 - 大图显示 */
.wechat-image-grid.single-image .wechat-image {
  width: 100%;
  height: 400rpx;
  border-radius: 15rpx;
}

/* 两张图片 - 并排显示 */
.wechat-image-grid.double-image {
  display: flex;
  flex-wrap: nowrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.double-image .wechat-image {
  flex: 1;
  height: 200rpx;
  border-radius: 15rpx;
  min-width: 0;
}

/* 三张图片 - 水平平均分布一行展示 */
.wechat-image-grid.triple-image {
  display: flex;
  flex-wrap: nowrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.triple-image .wechat-image {
  flex: 1;
  height: 200rpx;
  border-radius: 15rpx;
  min-width: 0;
}

/* 四张图片 - 2x2网格 */
.wechat-image-grid.quadruple-image {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.quadruple-image .wechat-image {
  width: calc(50% - 2rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

/* 五张图片 - 特殊布局（第一行2张，第二行3张） */
.wechat-image-grid.five-image {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.five-image .wechat-image:nth-child(1),
.wechat-image-grid.five-image .wechat-image:nth-child(2) {
  width: calc(50% - 2rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

.wechat-image-grid.five-image .wechat-image:nth-child(3),
.wechat-image-grid.five-image .wechat-image:nth-child(4),
.wechat-image-grid.five-image .wechat-image:nth-child(5) {
  width: calc(33.333% - 3rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

/* 六张图片 - 2x3网格 */
.wechat-image-grid.six-image {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.six-image .wechat-image {
  width: calc(33.333% - 3rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

/* 七张图片 - 特殊布局（第一行3张，第二行2张，第三行2张） */
.wechat-image-grid.seven-image {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.seven-image .wechat-image:nth-child(1),
.wechat-image-grid.seven-image .wechat-image:nth-child(2),
.wechat-image-grid.seven-image .wechat-image:nth-child(3) {
  width: calc(33.333% - 3rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

.wechat-image-grid.seven-image .wechat-image:nth-child(4),
.wechat-image-grid.seven-image .wechat-image:nth-child(5) {
  width: calc(50% - 2rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

.wechat-image-grid.seven-image .wechat-image:nth-child(6),
.wechat-image-grid.seven-image .wechat-image:nth-child(7) {
  width: calc(50% - 2rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

/* 八张图片 - 特殊布局（第一行3张，第二行3张，第三行2张） */
.wechat-image-grid.eight-image {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.eight-image .wechat-image:nth-child(1),
.wechat-image-grid.eight-image .wechat-image:nth-child(2),
.wechat-image-grid.eight-image .wechat-image:nth-child(3) {
  width: calc(33.333% - 3rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

.wechat-image-grid.eight-image .wechat-image:nth-child(4),
.wechat-image-grid.eight-image .wechat-image:nth-child(5),
.wechat-image-grid.eight-image .wechat-image:nth-child(6) {
  width: calc(33.333% - 3rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

.wechat-image-grid.eight-image .wechat-image:nth-child(7),
.wechat-image-grid.eight-image .wechat-image:nth-child(8) {
  width: calc(50% - 2rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

/* 九张图片 - 3x3网格 */
.wechat-image-grid.nine-image {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  width: 100%;
}

.wechat-image-grid.nine-image .wechat-image {
  width: calc(33.333% - 3rpx);
  height: 200rpx;
  border-radius: 15rpx;
}

/* 图片通用样式 */
.wechat-image {
  object-fit: cover;
  background-color: #f5f5f5;
}

/* 操作栏 */
.post-actions {
  display: flex;
  justify-content: flex-end;
  gap: 40rpx;
}

.action-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8rpx;
  cursor: pointer;
}

.action-icon {
  width: 32rpx;
  height: 32rpx;
}

.action-text {
  font-size: 24rpx;
  color: #666;
}
</style>